package com.haidechizi.backup.sort1;

import java.util.Arrays;

public class MergeSort {

    public static void main(String[] args) {
        int[] arr = new int[]{2, 3, 5, 0, 1, 4, 6, 100};
        mergeSort(arr, 0, arr.length - 1);
//        merge(arr, 0, 2, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    public static void mergeSort(int[] arr, int low, int high) {
        if (low >= high) {
            return;
        }
        int middle = (high + low) / 2;
        mergeSort(arr, low, middle);
        mergeSort(arr, middle + 1, high);
        merge(arr, low, middle, high);

    }


    public static void merge(int[] arr, int start, int middle, int end) {
        int length = (end - start) + 1;
        int[] tempArr = new int[length];

        int low = start;
        int high = middle + 1;
        int index = 0;
        while (low <= middle && high <= end) {
            while (low <= middle && arr[low] <= arr[high]) {
                tempArr[index] = arr[low];
                index++;
                low++;
            }
            while (high <= end && arr[high] < arr[low]) {
                tempArr[index] = arr[high];
                high++;
                index++;
            }
        }
        while (low <= middle) {
            tempArr[index] = arr[low];
            index++;
            low++;
        }
        while (high <= end) {
            tempArr[index] = arr[high];
            high++;
            index++;
        }

        // 将临时数组中的数写入到原数组
        for (int i = 0; i < tempArr.length; i++) {
            arr[start + i] = tempArr[i];
        }
    }
}
